package com.study.web.thread;

import com.study.utils.SysUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author study
 * @version 1.0
 * @date 2020/8/18 22:48
 */
@Slf4j
@RestController
@Api(tags = "线程测试")
@RequestMapping("/thread")
public class ThreadController {
    @Autowired
    private ExecutorService executor;

    @GetMapping("calc")
    public ResponseEntity calc() throws ExecutionException, InterruptedException {
        System.out.println(SysUtils.getDateSpan());
        CompletableFuture<Void> getSkuInfoFuture = CompletableFuture.runAsync(() -> {
            //1、远程查询当前要添加商品的信息
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, executor);

        //开启第二个异步任务
        CompletableFuture<Void> getSkuAttrValuesFuture = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, executor);
        //等待所有的异步任务全部完成
        CompletableFuture.allOf(getSkuInfoFuture, getSkuAttrValuesFuture).get();
        System.out.println(SysUtils.getDateSpan());
        return ResponseEntity.ok("");
    }

}
